import { ResTree, createTree } from './entity';
import { request } from 'ice';

export interface QueryParams {
  parentId?: number;
  /** 资源名称 */
  name?: string;
  /** 资源类型 */
  type?: number;
}

export interface DetailVO {
  id?: number;
  parentId?: number;
  /** 资源名称 */
  name?: string;
  /** 资源类型 */
  type?: number;
  /** 资源uri */
  uri?: string;
  /** 资源图标 */
  icon?: string;
  /** 资源备注 */
  remark?: string;
  /** 用户状态 */
  status?: number;
  /** 资源排序 */
  sort?: number;
  /** 创建日期 */
  createTime?: number;
}

/** 列表 */
export const resList = (pageParams: ICommon.PageParams, formData: QueryParams): Promise<any> => {
  const params = {
    ...pageParams,
    ...formData,
  };
  return request.get('/erp/privilege/list', { params }).then((res) => ({
    total: res?.total || 0,
    list: res?.data || [],
  }));
};

/** 保存资源 */
export const saveRes = (params?: DetailVO): Promise<void> => {
  return request.post('/erp/privilege/save', { ...params });
};

/** 删除资源 */
export const deleteRes = (id?: number): Promise<void> => {
  return request.get('/erp/privilege/delete', { params: { id } });
};

export interface ResApi {
  /** 资源id */
  privilegeId: number;
  uriList?: ResApiDetail[];
}

export interface ResApiDetail {
  /** 资源id */
  privilegeId: number;
  /** 接口路径 */
  path: number;
  /** 接口方法 */
  method: number;
}

/** 获取资源接口列表 */
export const resApiList = (privilegeId?: number): Promise<ResApiDetail[]> => {
  return request.get('/erp/privilege/api/list', { params: { privilegeId } });
};


/** 获取api树 */
export const apiTree = (): Promise<ResTree[]> => {
  return request.get('/erp/backend/uri/tree').then((res) => createTree(res));
};

/**
 * 资源授权
 * @param params 保存参数
 * @returns null
 */
export const resSaveApi = (params?: ResApi): Promise<void> => {
  return request.post('/erp/privilege/api/save', { ...params });
};
